package com.deram.ctin.serv.third.utils;

import com.deram.ctin.common.bean.UploadResult;
import com.deram.ctin.common.consts.ErrorConsts;
import com.deram.ctin.common.error.BusinessException;
import com.deram.ctin.common.utils.JsonUtils;
import com.deram.ctin.serv.third.result.QiniuUpdateConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

public class QiniuUploadUtils {

    private static final Logger logger = LoggerFactory.getLogger(QiniuUploadUtils.class);

    public static UploadResult upload(QiniuUpdateConfig config, String key, MultipartFile uploadFile) {
        InputStream inputStream;
        try {
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new BusinessException(ErrorConsts.BUSINESS, "获取文件流失败");
        }
        return upload(config, key, inputStream);
    }

    public static UploadResult upload(QiniuUpdateConfig config, String key, InputStream inputStream){
        UploadManager uploadManager = createUploadManager();
        DefaultPutRet putRet;
        try {
            Response response = uploadManager.put(inputStream, key, config.getToken(),null, null);
            putRet = JsonUtils.fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException e) {
            logger.error(e.getMessage(), e);
            throw new BusinessException(ErrorConsts.BUSINESS, "七牛云上传失败");
        }
        UploadResult result = new UploadResult();
        result.setName(putRet.key);
        result.setUrl(config.getUploadDomain() + "/" + putRet.key);
        return result;
    }

    private static UploadManager createUploadManager(){
        Configuration cfg = new Configuration(Zone.autoZone());
        UploadManager uploadManager = new UploadManager(cfg);
        return uploadManager;
    }
}
